<template>
  <span>
    <!-- <transition name="fade-in-linear"> -->
    <div v-show="showPopover" ref="popover" class="data-popover">
      <slot></slot>
    </div>
    <!-- </transition> -->
  </span>
</template>
<script>
import { createPopperLite as createPopper } from "@popperjs/core";
export default {
  name: "DPopover",
  props: {
    value: Boolean,
    reference: null
  },
  data() {
    return {
      showPopover: false
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.showPopover = val;
        this.$emit("input", val);
      }
    },
    reference: {
      handler(val) {
        if (val) this.updatePopper();
      }
    },
    showPopover(val) {
      val ? this.updatePopper() : this.destroyPopper();
      this.$emit("input", val);
    }
  },
  mounted() {
    document.addEventListener("click", this.handlerDocumentClick);
  },
  destroyed() {
    document.removeEventListener("click", this.handlerDocumentClick);
  },
  methods: {
    handlerDocumentClick(e) {
      let reference = this.reference;
      let popover = this.$refs.popover;

      if (!reference || reference.contains(e.target) || !popover || popover.contains(e.target))
        return;

      this.showPopover = false;
    },
    createPopper() {
      let reference = this.reference || this.$refs.reference;
      let popover = this.popover || this.$refs.popover;
      this.popperJs = createPopper(reference, popover);
    },
    updatePopper() {
      if (this.popperJs) {
        this.popperJs.update();
      } else {
        this.createPopper();
      }
    },
    destroyPopper() {
      if (this.popperJs) {
        this.popperJs.destroy();
        this.popperJs = null;
      }
    }
  }
};
</script>
<style lang="scss">
.data-popover {
  position: absolute;
  box-shadow: 0 2px 12px 0 rgba(#000, 0.1);
  border-radius: 4px;
  border: 1px solid #ebeef5;
  // font-size: 12px;
  background: #fff;
  // transform: translate3d(49px, 136px, 0px) !important;
}
</style>
